package ui.component {

	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	
	public class Button extends Sprite implements IUIComponent {
		
		protected var skin:Bitmap;
		protected var upSkin:BitmapData;
		protected var overSkin:BitmapData;
		protected var outSkin:BitmapData;
		protected var state:uint;
		protected var _handler:Function;
		protected var _enable:Boolean = true;
		
		public static const UP_STATE:uint = 1;
		public static const OVER_STATE:uint = 2;
		public static const OUT_STATE:uint = 3;
		
		public var id:uint;

		public function Button(upData:BitmapData, overData:BitmapData, outData:BitmapData, handler:Function) {
			super();
			
			skin = new Bitmap();
			addChildAt(skin, 0);
			updateSkin(upData, overData, outData);
			updateState(UP_STATE);
			addListeners();
			_handler = handler;
			buttonMode = true;
		}
		
		public function updateSkin(upData:BitmapData, overData:BitmapData, outData:BitmapData):void {
			upSkin = upData;
			overSkin = overData;
			outSkin = outData;
		}
		
		private function addListeners():void {
			addEventListener(MouseEvent.CLICK, clickHandler);
			addEventListener(MouseEvent.ROLL_OVER, overHandler);
			addEventListener(MouseEvent.ROLL_OUT, outHandler);
		}
		
		protected function clickHandler(event:MouseEvent):void {
			if (!_enable) {
//				return;
			}
			if (_handler != null) {
				_handler(this);
			}
		}
		
		protected function overHandler(event:MouseEvent):void {
			if (!_enable) {
				return;
			}
			updateState(OVER_STATE);
		}
		
		protected function outHandler(event:MouseEvent):void {
			if (!_enable) {
				return;
			}
			updateState(OUT_STATE);
		}
		
		public function updateState(data:uint):void {
			switch (data) {
				case UP_STATE:
					skin.bitmapData = upSkin;
					break;
				case OVER_STATE:
					skin.bitmapData = overSkin;
					break;
				case OUT_STATE:
					skin.bitmapData = outSkin;
					break;
			}
			state = data;
		}
		
		public function setIcon(bmd:BitmapData):void {
			skin.bitmapData = bmd;
		}
		
		public function set enable(value:Boolean):void {
			_enable = value;
		}
		
		public function dispose():void {
			skin.bitmapData = null;
			removeEventListener(MouseEvent.CLICK, clickHandler);
			removeEventListener(MouseEvent.ROLL_OVER, overHandler);
			removeEventListener(MouseEvent.ROLL_OUT, outHandler);
		}
	}
}